﻿using Microsoft.Extensions.Configuration;
using Timo.SqlSugar.DbContext;

namespace Timo.SqlSugar;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        //检查ConfigId配置
        CheckSameConfigId();
        services.AddSqlSugarSetup(App.Configuration);
        var timoDB = SqlSugarDBConfig.DbConfigs.FirstOrDefault(t=>t.ConfigId == "Timo");
        services.AddSugarDbContext<TimoDBContext>(App.Configuration, timoDB, App.HostEnvironment.IsDevelopment());
        // 多库上下文
        services.AddSugarMultipleDbContext<MultipleDBContext>(App.Configuration, App.HostEnvironment.IsDevelopment() , 
            (typeof(TimoDBContext), timoDB)
        );
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }

    /// <summary>
    /// 检查是否有相同的ConfigId
    /// </summary>
    /// <returns></returns>
    private static void CheckSameConfigId()
    {
        var configIdGroup = SqlSugarDBConfig.DbConfigs.GroupBy(it => it.ConfigId).ToList();
        foreach (var configId in configIdGroup)
        {
            if (configId.ToList()?.Count > 1) throw Oops.Oh($"Sqlsugar连接配置ConfigId:{configId.Key}重复了");
        }
    }
}